﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;

namespace ArgusPCLib.Bird
{
	/// <include file='Documentation/ResourceInfoServer.xml' path='ResourceInfoServer/*' />
	public static class ResourceInfoServer
	{
		/// <summary>
		/// Gets the value of the href-attribute of a html element.
		/// </summary>
		/// <example>For a example, see <see cref="ResourceInfoServer"/>.</example>
		/// <param name="serverAdress">The adress of a html page which contains the element.</param>
		/// <param name="linkId">The value of the id-attribute of the html element.</param>
		/// <returns>The value of the href-attribute if an element with the specified id was found, otherwise <c>null</c>.</returns>
		public static async Task<Uri> GetUriAsync(Uri serverAdress, string linkId)
		{
			Uri[] uris = await ResourceInfoServer.GetUrisAsync(serverAdress, new string[] { linkId });
			return uris[0];
		}

		/// <summary>
		/// Gets the values of the href-attribute of multiple html elements.
		/// </summary>
		/// <example>For a example, see <see cref="ResourceInfoServer"/>.</example>
		/// <param name="serverAdress">The adress of a html page which contains the elements.</param>
		/// <param name="linkId">The values of the id-attribute of the html elements.</param>
		/// <returns>An array of the same length as <paramref name="linkId"/> containing the values of the href-attribute of the html elements which where found and <c>null</c> for the others.</returns>
		public static async Task<Uri[]> GetUrisAsync(Uri serverAdress, params string[] linkId)
		{
			if (linkId == null || linkId.Length < 1)
				return null;

			if (serverAdress == null)
				throw new ArgumentNullException("serverAdress");

			using (HttpClient httpClient = new HttpClient())
			{
				string html;
				try { html = await httpClient.GetStringAsync(serverAdress); }
				catch { return null; }
				string htmlLower = html.ToLowerInvariant();
				Uri[] RetVal = new Uri[linkId.Length];
				for (int i = 0; i < linkId.Length; i++)
				{
					int index = htmlLower.IndexOf("id=\"" + linkId[i].ToLowerInvariant() + '\"');
					if (index < 0)
					{
						RetVal[i] = null;
					}
					else
					{
						index = htmlLower.LastIndexOf('<', index);
						int end = htmlLower.IndexOf('>', index);
						index = htmlLower.IndexOf("href=", index, end - index);
						if (index < 0)
						{
							RetVal[i] = null;
						}
						else
						{
							index += 6;
							end = htmlLower.IndexOf('\"', index);
							string link = html.Substring(index, end - index);
							RetVal[i] = new Uri(link);
						}
					}
				}
				return RetVal;
			}
		}
	}
}
